/**
 * 对公众平台发送给公众账号的消息加解密示例代码.
 * 
 * @copyright Copyright (c) 1998-2014 Tencent Inc.
 */

// ------------------------------------------------------------------------

package com.dangz.dans.aes;

import com.dangz.dans.model.News;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import java.io.StringReader;
import java.util.List;

/**
 * XMLParse class
 *
 * 提供提取消息格式中的密文及生成回复消息格式的接口.
 */
public class XMLParse {

	/**
	 * 提取出xml数据包中的加密消息
	 * @param xmltext 待提取的xml字符串
	 * @return 提取出的加密消息字符串
	 * @throws AesException 
	 */
	public static Object[] extract(String xmltext) throws AesException     {
		Object[] result = new Object[3];
		try {
			DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
			DocumentBuilder db = dbf.newDocumentBuilder();
			StringReader sr = new StringReader(xmltext);
			InputSource is = new InputSource(sr);
			Document document = db.parse(is);

			Element root = document.getDocumentElement();
			NodeList nodelist1 = root.getElementsByTagName("Encrypt");
			NodeList nodelist2 = root.getElementsByTagName("ToUserName");
			result[0] = 0;
			result[1] = nodelist1.item(0).getTextContent();
			result[2] = nodelist2.item(0).getTextContent();
			return result;
		} catch (Exception e) {
			e.printStackTrace();
			throw new AesException(AesException.ParseXmlError);
		}
	}

	public static Object[] denctryXml(String xmltext) throws AesException     {
		Object[] result = new Object[8];
		try {
			DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
			DocumentBuilder db = dbf.newDocumentBuilder();
			StringReader sr = new StringReader(xmltext);
			InputSource is = new InputSource(sr);
			Document document = db.parse(is);

			Element root = document.getDocumentElement();
			NodeList nodelist1 = root.getElementsByTagName("MsgType");
			NodeList nodelist2 = root.getElementsByTagName("ToUserName");
			NodeList nodelist3 = root.getElementsByTagName("FromUserName");
			NodeList nodelist4 = root.getElementsByTagName("Event");
			NodeList nodelist5 = root.getElementsByTagName("Content");
			//MsgType
			result[0] = 0;
			result[1] = nodelist1.item(0).getTextContent();
			result[2] = nodelist2.item(0).getTextContent();
			result[3] = nodelist3.item(0).getTextContent();
			if (nodelist4.getLength() > 0){
				result[4] = nodelist4.item(0).getTextContent(); // 用户的操作。
			}
			if (nodelist5.getLength() > 0){
				result[5] = nodelist5.item(0).getTextContent(); // 用户的操作。
			}
			return result;
		} catch (Exception e) {
			e.printStackTrace();
			throw new AesException(AesException.ParseXmlError);
		}
	}

	public static String  newsType(String to,String from,List<News> news){
		StringBuffer sb = new StringBuffer();
		sb.append("<xml>");
		sb.append("<ToUserName><![CDATA["+to+"]]></ToUserName>");
		sb.append("<FromUserName><![CDATA["+from+"]]></FromUserName>");
		sb.append("<CreateTime>11111111</CreateTime>");
		sb.append("<MsgType><![CDATA[news]]></MsgType>");
		sb.append("<ArticleCount>" + news.size() + "</ArticleCount>");
		sb.append("<Articles>");
		for (News n : news) {
			sb.append("<item>");
			sb.append("<Title><![CDATA["+n.getTitle()+"]]></Title> ");
			sb.append("<Description><![CDATA["+n.getDesc()+"]]></Description>");
			sb.append("<PicUrl><![CDATA["+n.getUrl()+"]]></PicUrl>");
			sb.append("<Url><![CDATA["+n.getHttpurl()+"]]></Url>");
			sb.append("</item>");
		}
		sb.append("</Articles>");
		sb.append("</xml>");
		return sb.toString();
	}

	public static String newsText(String to,String from,String content){
		StringBuffer sb = new StringBuffer();
		sb.append("<xml>");
		sb.append("<ToUserName><![CDATA["+to+"]]></ToUserName>");
		sb.append("<FromUserName><![CDATA["+from+"]]></FromUserName>");
		sb.append("<CreateTime>11111111</CreateTime>");
		sb.append("<MsgType><![CDATA[news]]></MsgType>");
		sb.append("<Content>"+content+"</Content>");
		sb.append("</xml>");
		return sb.toString();
	}

	/**
	 * 生成xml消息
	 * @param encrypt 加密后的消息密文
	 * @param signature 安全签名
	 * @param timestamp 时间戳
	 * @param nonce 随机字符串
	 * @return 生成的xml字符串
	 */
	public static String generate(String encrypt, String signature, String timestamp, String nonce) {

		String format = "<xml>\n" + "<Encrypt><![CDATA[%1$s]]></Encrypt>\n"
				+ "<MsgSignature><![CDATA[%2$s]]></MsgSignature>\n"
				+ "<TimeStamp>%3$s</TimeStamp>\n" + "<Nonce><![CDATA[%4$s]]></Nonce>\n" + "</xml>";
		return String.format(format, encrypt, signature, timestamp, nonce);

	}
}
